package com.sparkflow.mysqlbinlog.clickhousesync.service.metadata;


import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 表元数据缓存类
 * 负责缓存和管理表结构元数据信息
 *
 * @author Mr_xiaoZH
 * @date 2025-07-23
 */
public class TableMetadataCache {

    private final Map<String, TableMetadata> cache = new HashMap<>();

    public void addTableMetadata(String tableName, List<Map<String, Object>> columnInfos, List<String> columns, String primaryKey, Map<String, String> columnTypeMap) {
        cache.put(tableName, new TableMetadata(columnInfos, columns, primaryKey, columnTypeMap));
    }

    public List<Map<String, Object>> getColumnInfos(String tableName) {
        TableMetadata metadata = cache.get(tableName);
        if (metadata == null) {
            throw new IllegalArgumentException("Table metadata not found for table: " + tableName);
        }
        return metadata.getColumnInfos();
    }
    public List<String> getTableColumns(String tableName) {
        TableMetadata metadata = cache.get(tableName);
        if (metadata == null) {
            throw new IllegalArgumentException("Table metadata not found for table: " + tableName);
        }
        return metadata.getColumns();
    }

    public String getPrimaryKey(String tableName) {
        TableMetadata metadata = cache.get(tableName);
        if (metadata == null) {
            throw new IllegalArgumentException("Table metadata not found for table: " + tableName);
        }
        return metadata.getPrimaryKey();
    }

    public Map<String, String> getColumnTypeMap(String tableName) {
        TableMetadata metadata = cache.get(tableName);
        if (metadata == null) {
            throw new IllegalArgumentException("Table metadata not found for table: " + tableName);
        }
        return metadata.getColumnTypeMap();
    }

    public boolean containsTable(String tableName) {
        return cache.containsKey(tableName);
    }

    @Getter
    @Setter
    private static class TableMetadata {
        private final List<Map<String, Object>> columnInfos;
        private final List<String> columns;
        private final String primaryKey;
        private final Map<String, String> columnTypeMap; // 存储字段名 -> 类型

        public TableMetadata(List<Map<String, Object>> columnInfos, List<String> columns, String primaryKey, Map<String, String> columnTypeMap) {
            this.columnInfos = columnInfos;
            this.columns = columns;
            this.primaryKey = primaryKey;
            this.columnTypeMap = columnTypeMap;
        }
    }
}
